from Data import search_file
import os
import win32com.client
import pythoncom
import time

sysop_flag = False
pdf_paths = []


# pdf转换
def pdf_conversion(filepaths):
    # global sysop_flag
    if filepaths is None:
        filepaths = search_file.select_folder()
    if filepaths == "-1":
        return "-1"
    # print(filepaths)
    conversion(filepaths)


def conversion(filepaths):
    global pdf_paths
    global sysop_flag

    try:
        # 初始化Word应用
        word = win32com.client.Dispatch("Word.Application")
        word.Visible = False

        root_path = os.path.commonpath(filepaths)
        # print(root_path)
        if "维护命令" in root_path:
            pdf_root=f'{root_path.rsplit("维护命令",1)[0]}\\PDF\\维护命令'
        elif "诊断命令" in root_path:
            pdf_root=f'{root_path.rsplit("诊断命令",1)[0]}\\PDF\\诊断命令'
        else:
            pdf_root = f'{root_path}\\PDF'
        # print(pdf_root)
        # 创建PDF根目录
        if not os.path.exists(pdf_root):
            os.makedirs(pdf_root)
            print(f"创建PDF根目录: {pdf_root}")

        # 处理每个文件
        for filepath in filepaths:
            try:
                if not filepath.lower().endswith(('.doc', '.docx')):
                    continue

                # 创建对应的PDF目录结构
                rel_path = os.path.relpath(os.path.dirname(filepath), root_path)
                pdf_dir = os.path.join(pdf_root, rel_path)
                if not os.path.exists(pdf_dir):
                    os.makedirs(pdf_dir)

                # 设置PDF文件路径
                pdf_name = os.path.splitext(os.path.basename(filepath))[0] + '.pdf'
                pdf_path = os.path.join(pdf_dir, pdf_name)

                # 转换文件
                doc = word.Documents.Open(filepath)

                # 配置PDF选项
                doc.ExportAsFixedFormat(
                    OutputFileName=pdf_path,
                    ExportFormat=17,  # wdExportFormatPDF = 17
                    OpenAfterExport=False,
                    OptimizeFor=0,  # wdExportOptimizeForPrint = 0
                    CreateBookmarks=1,  # wdExportCreateHeadingBookmarks = 1
                    DocStructureTags=True,
                    BitmapMissingFonts=True,
                    UseISO19005_1=False
                )

                doc.Close()
                print(f"已转换: {filepath} -> {pdf_path}")
                pdf_paths.append(pdf_path)
            except Exception as e:
                print(f"\033[91m转换文件失败 {filepath}: {str(e)}\033[0m")
                sysop_flag = True
                continue

        word.Quit()
        print("\033[92m所有文件转换完成！\033[0m")

    except Exception as e:
        print(f"\033[91m转换过程出错: {str(e)}\033[0m")
        sysop_flag = True
        if 'word' in locals():
            word.Quit()


if __name__ == '__main__':
    pdf_conversion(None)
